package com.assistant.codegen.modules.model.domain.column;

import com.assistant.codegen.modules.model.domain.Model;
import com.assistant.framework.BaseDomain;
import com.assistant.util.StringUtils;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.*;
import javax.persistence.Table;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 字段
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
@Table(name = "codegen_project_model_column")
public abstract class ModelColumn extends BaseDomain<ModelColumn> {

    @ManyToOne
    @JoinColumn(name = "model_id", foreignKey = @ForeignKey(name = "none"), insertable = false, updatable = false)
    private Model model;

    private String propertyName;
    /**
     * 数据库中的列名
     */
    @Column(name = "column_name")
    private String columnName;

    private String comment;

    private boolean notNull = true;

    /**
     * 字段的序号
     */
    private int sort = 99;

    public abstract Class<?> getJavaType();

    public String getColumnDefinition() {
        return getColumnTypeDefinition() + (isNotNull() ? "" : " null") + (StringUtils.hasLength(getComment()) ? (" comment " + "'" + getComment() + "'") : "");
    }

    public abstract String getColumnTypeDefinition();

    protected void assign(ResultSet resultSet) throws SQLException {
        this.columnName = resultSet.getString("COLUMN_NAME");
        this.propertyName = StringUtils.toLowerCase4Index(StringUtils.toCamelCase(this.columnName));
        this.comment = resultSet.getString("REMARKS");
    }
}
